package com.supcon.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.util.Map;

/**
 * 分页工具
 *
 * @author Chill
 */
public class Condition {

    /**
     * 转化成mybatis plus中的Page
     *
     * @param query
     * @return
     */
    public static <T> IPage<T> getPage(Query query) {
        if(query !=null) {
            Integer currentIndex = query.getCurrentPage();
            currentIndex =currentIndex ==null || currentIndex <= 0 ? 1 : currentIndex;
            Integer size = query.getPageSize();
            size =size == null || size <= 0 ? 10 : size;

            Page<T> page = new Page<>(currentIndex, size);

            if (query.getOrder() != null && query.getOrder().length() > 0 && query.getSorter() !=null && query.getSorter().length()>0) {
                if(query.getOrder() =="ascend"){
                    page.setAsc(query.getSorter().split(","));
                }
                else{
                    page.setDesc(query.getSorter().split(","));
                }
            }

            return page;
        }
        else {
            return  new Page<>(1, 10);
        }
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param entity
     * @param <T>
     * @return
     */
    public static <T> QueryWrapper<T> getQueryWrapper(T entity) {
        return new QueryWrapper<>(entity);
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param query
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> query, Class<T> clazz) {
        query.remove("currentPage");
        query.remove("pageSize");
        query.remove("sorter");
        query.remove("order");
        QueryWrapper<T> qw = new QueryWrapper<>();
        qw.setEntity(BeanUtils.instantiateClass(clazz));
        if (query != null && query.size()>0) {
            query.forEach((k, v) -> {
                if (v != null) {
                    qw.like(humpToUnderline(k), v);
                }
            });
        }
        return qw;
    }

    private static String humpToUnderline(String para) {
        para = lowerFirst(para);
        StringBuilder sb = new StringBuilder(para);
        int temp = 0;
        for (int i = 0; i < para.length(); i++) {
            if (Character.isUpperCase(para.charAt(i))) {
                sb.insert(i + temp, "_");
                temp += 1;
            }
        }
        return sb.toString().toLowerCase();
    }

    private static String lowerFirst(String str) {
        char firstChar = str.charAt(0);
        if (firstChar >= 'A' && firstChar <= 'Z') {
            char[] arr = str.toCharArray();
            arr[0] += ('a' - 'A');
            return new String(arr);
        }
        return str;
    }


}